import java.util.ArrayList;

/**
 * @author mubei
 * @date 2021/12/9
 * @description
 */
public class Demo {

    public static void main(String[] args) {
        int [][] matrix = {{1,2},{3,4}};
        ArrayList<Integer> res = new ArrayList<Integer>();
        int map[][] = new int[matrix.length][matrix[0].length];

        int dx[] = {0,1,0,-1};
        int dy[] = {1,0,-1,0};
        int d = 0;
        int x = 0,y = 0;
        int n = matrix.length , m = matrix[0].length;
        for (int i = 0; i < n * m; i ++){
            if(x >=0 && x < n && y >= 0 && y < m && map[x][y] == 0){
                res.add(matrix[x][y]);

                map[x][y] = 1;
                x += dx[d%4];
                y += dy[d%4];
            }else{
                x -= dx[d%4];
                y -= dy[d%4];
                d += 1;
                x += dx[d%4];
                y += dy[d%4];
                res.add(matrix[x][y]);
                map[x][y] = 1;
                x += dx[d%4];
                y += dy[d%4];
            }
        }

        for (Integer re : res) {
            System.out.print(re+" ");
        }
    }
}
